import rentBillDao from "#/dao/rentBill";
import type { RentBill, BaseService } from "#/types";
import {
  getUuid,
  logger,
  codeSuccess,
  codeFail,
  getCurrentTime,
} from "#/utils";
/**
 * 租房管理实现类
 */
class RentBillService implements BaseService<RentBill> {
  async queryList({ page, pageSize, date, settle_utilities = "" }) {
    try {
      const data = await rentBillDao.queryList({
        page,
        pageSize,
        date,
        settle_utilities,
      });
      //获取总计
      const getTotal = async () => {
        if (date) {
          return 1;
        }
        if (settle_utilities !== "") {
          const [{ total }] = await rentBillDao.queryTotalByStatus(
            settle_utilities
          );
          return total;
        }
        const [{ total }] = await rentBillDao.queryTotal();
        return total;
      };

      if (data) {
        return codeSuccess({
          items: data,
          total: await getTotal(),
        });
      }
      return codeFail("查询失败");
    } catch (error) {
      logger(error);
      return codeFail(error);
    }
  }
  async insert(params: RentBill) {
    try {
      const rank = await this.getRank();
      logger("rank" + rank);
      const r = await rentBillDao.insert({
        ...params,
        id: getUuid(),
        created_time: getCurrentTime(),
        rank,
      });
      if (r) {
        return codeSuccess(r);
      }
      return codeFail("添加失败");
    } catch (error) {
      logger(error);
      return codeFail(error);
    }
  }
  async deleteById(id: string) {
    try {
      const r = await rentBillDao.deleteById(id);
      if (r) {
        return codeSuccess(r);
      }
      return codeFail("删除失败");
    } catch (error) {
      logger(error);
      return codeFail(error);
    }
  }
  async update(params) {
    try {
      const r = await rentBillDao.update(params);
      if (r) {
        return codeSuccess(r);
      }
      return codeFail("更新失败");
    } catch (error) {
      logger(error);
    }
  }
  async queryRentTotal() {
    try {
      const r = await rentBillDao.queryRentTotal();
      if (r) {
        return codeSuccess(r[0]);
      }
      return codeFail("查询失败");
    } catch (error) {
      logger(error);
    }
  }
  private async getRank() {
    const [{ maxRank }] = await rentBillDao.getMaxRank();
    logger(JSON.stringify(maxRank));
    if (maxRank) {
      return maxRank + 1;
    }
    return 1;
  }
}

export default new RentBillService();
